﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Budget
{
    public partial class ExpenseListByCategory : Form
    {
        public decimal total=0;
        DataTable dt_expenses;
        public ExpenseListByCategory()
        {
            InitializeComponent();

            dbData.PopulateDDLFromDictionary(dbData.GetExpenseCategoryDict(), ddlCategory);
            ddlCategory.Items.Insert(0, "All Categories");
            if(ddlCategory.Items.Count > 0)
            {
                ddlCategory.SelectedIndex = 0;
            }
            int fridays = Dates.getWeeksInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year);
            this.expensesForDatesTableAdapter.Fill(this.budgetDataSet.ExpensesForDatesDataTable
                , (Dates.getFirstFridayInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year).AddDays(-6))
                , Dates.getFirstFridayInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year).AddDays((fridays - 1) * 7));
        }
        public ExpenseListByCategory(string _cat, DateTime _date)
        {
            InitializeComponent();
            dbData.PopulateDDLFromDictionary(dbData.GetExpenseCategoryDict(), ddlCategory);
            ddlCategory.Items.Insert(0, "All Categories");
            try
            {
                ddlCategory.SelectedIndex = dbData.GetIndexFromDDLBasedOnSubString(_cat, ddlCategory);
            }
            catch
            {
                MessageBox.Show("Category Not Found!");
            }
            dateTimePicker1.Value = _date;
            //int fridays = Dates.getWeeksInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year);
            //this.expensesForDatesTableAdapter.Fill(this.budgetDataSet.ExpensesForDatesDataTable
            //    , (Dates.getFirstFridayInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year).AddDays(-6))
            //    , Dates.getFirstFridayInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year).AddDays((fridays - 1) * 7));
            UpdateData();
        }


        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateData();
        }
        private void UpdateData()
        {
            lv_trans_by_cat.Clear();
            AddExpensesToListView();

            //gridview
            int fridays = Dates.getWeeksInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year);
            this.budgetDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
            this.expensesForDatesTableAdapter.Fill(this.budgetDataSet.ExpensesForDatesDataTable
                , (Dates.getFirstFridayInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year).AddDays(-6))
                , Dates.getFirstFridayInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year).AddDays((fridays - 1) * 7));
            dataGridView1.DataSource = this.expensesForDatesDataTableBindingSource;
        }
        private void AddExpensesToListView()
        {
            total = 0;
            lv_trans_by_cat.FullRowSelect = true;
            lv_trans_by_cat.View = View.Details;
            int fridays = Dates.getWeeksInMonth(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year);
            List<ListViewGroup> ExpenseGroup = new List<ListViewGroup>();
            lv_trans_by_cat.Columns.Add("ID", 1, HorizontalAlignment.Left);
            lv_trans_by_cat.Columns.Add("Date", 150, HorizontalAlignment.Left);
            lv_trans_by_cat.Columns.Add("Desc", 400, HorizontalAlignment.Left);
            lv_trans_by_cat.Columns.Add("Company", 125, HorizontalAlignment.Left);
            lv_trans_by_cat.Columns.Add("Location", 125, HorizontalAlignment.Left);
            lv_trans_by_cat.Columns.Add("Amount", 150, HorizontalAlignment.Left);
            foreach (DateTime dt in Dates.getFridaysInMonthList(dateTimePicker1.Value.Month, dateTimePicker1.Value.Year))
            {
                ExpenseGroup.Add(new ListViewGroup(dt.ToString("MM/dd/yyyy"), System.Windows.Forms.HorizontalAlignment.Left));
                lv_trans_by_cat.Groups.Add(ExpenseGroup[ExpenseGroup.Count - 1]);
            }

            List<ListViewItem> ExpenseList = new List<ListViewItem>();
            ListViewItem item;
            //ExpenseCat.Group = ExpenseGroup;

            dt_expenses = DatabaseQuery.ExecStringProc(
                    StoredProcs.getExpenseForWeek(
                        (Dates.getFirstFridayInMonth(dateTimePicker1.Value.Month,dateTimePicker1.Value.Year).AddDays(-6)).ToString("MM/dd/yyyy"),
                        (Dates.getFirstFridayInMonth(dateTimePicker1.Value.Month,dateTimePicker1.Value.Year).AddDays((fridays-1)*7)).ToString("MM/dd/yyyy")
                                                 )
            );

            //loop through each row
            for (int i = 0; i < dt_expenses.Rows.Count; i++)
            {
                //we have all expenses in the data table, only add the ones from the selected category
                if (ddlCategory.SelectedItem.ToString() == "All Categories")
                {
                    ;
                }
                else if (dt_expenses.Rows[i]["tblExpenses.Category"].ToString() != ((KeyValuePair<int, string>)ddlCategory.SelectedItem).Key.ToString())
                {
                    continue;
                }
                //create a new row, first column is the date
                item = new ListViewItem(dt_expenses.Rows[i]["tblExpenses.ID"].ToString());
                DateTime temp_date = Dates.StringToDateTime(dt_expenses.Rows[i]["Date"].ToString());
                //set the group equal to the friday the purchase is associated with
                item.Group = ExpenseGroup[Dates.getFridayOfMonthIndex(temp_date)];
                //add subitems to the row
                item.SubItems.Add(Convert.ToDateTime(dt_expenses.Rows[i]["Date"].ToString()).ToString("dddd MM/dd/yyyy"));
                item.SubItems.Add(dt_expenses.Rows[i]["Description"].ToString());
                item.SubItems.Add(dt_expenses.Rows[i]["Company"].ToString());
                item.SubItems.Add(dt_expenses.Rows[i]["Location"].ToString());
                item.SubItems.Add("$"+dt_expenses.Rows[i]["Amount"].ToString());
                //store in list, we will add after we are done
                ExpenseList.Add(item);
                total += Convert.ToDecimal(dt_expenses.Rows[i]["Amount"]);
            }
            //populate the listview from out list
            foreach(ListViewItem lvi in ExpenseList)
            {
                lv_trans_by_cat.Items.Add(lvi);
            }
            lblTotalVal.Text = total.ToString();
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            int newcat = dbData.GetCategoryIDFromCategory(dataGridView1.Rows[e.RowIndex].Cells["Expr2"].Value.ToString());
            this.expensesForDatesTableAdapter.UpdateQuery(newcat,
                Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells["amountDataGridViewTextBoxColumn"].Value),
                Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells["dateDataGridViewTextBoxColumn"].Value.ToString()),
                dataGridView1.Rows[e.RowIndex].Cells["descriptionDataGridViewTextBoxColumn"].Value.ToString(),
                dataGridView1.Rows[e.RowIndex].Cells["Company"].Value.ToString(),
                Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["ID"].Value));
            UpdateData();
        }

        private void tabControl1_TabIndexChanged(object sender, EventArgs e)
        {

        }

        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            if (tabControl1.SelectedIndex == 0)
            {
                lblTotal.Visible = true;
                lblTotalVal.Visible = true;
            }
            else
            {
                lblTotal.Visible = false;
                lblTotalVal.Visible = false;
            }
        }

        private void lv_trans_by_cat_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void lv_trans_by_cat_DoubleClick(object sender, EventArgs e)
        {

        }

        private void lv_trans_by_cat_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo info =
                 this.lv_trans_by_cat.HitTest(
                 //e.Location
                 new Point(0//e.Location.X
                     , e.Location.Y
                 ));
            //MessageBox.Show(info.SubItem.Text + " clicked!");
            //int i=info.Item.SubItems.IndexOf(info.SubItem);

            int index;
            index = Convert.ToInt32(info.SubItem.Text);

            Add_Purchase ap = new Add_Purchase(index, Money.TransactionType.Expense);
            ap.ShowDialog();
            ap.Dispose();
            UpdateData();
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            UpdateData();
        }

        private void ExpenseListByCategory_Resize(object sender, EventArgs e)
        {
            if (Form1.ActiveForm != null)
            {
                tabControl1.Height = this.Height - 80 - tabControl1.Location.Y;
                tabControl1.Width = this.Width - 40;
            }
        }

        private void ExpenseListByCategory_Load(object sender, EventArgs e)
        {

        }
    }
}
